import React, { useState, useEffect, useRef } from 'react'
import { useNavigate  } from 'react-router-dom';
import { Form, Input, Toast, Button } from 'antd-mobile'
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import { change_username, change_site,change_site_name, change_token } from '@/Store/action';
import { connect } from 'react-redux';
import { checkTicket, getSiteInfo, listWorkshop, loginByUsername } from '@/api/login';
import "./index.less"

function Index({ location, change_username, change_site,change_site_name, change_token }) {
    const FormRef = useRef(null)
    const [visible, setVisible] = useState(false)
    const [loading, setLoading] = useState(false)
    const navigate = useNavigate();

    useEffect(() => {
        // getTicket()
    }, [])

    const handleLogin = async () => {
        if (loading) return
        let params = FormRef.current.getFieldValue()
        setLoading(true)
        try {
            let response = await loginByUsername(params)
            if (response) {
                const data = response.data;
                if (data.code == 1) {
                    Toast.show({
                        content: data.msg,
                    })
                } else {
                    await getInfoSIte(params.username)
                    change_username(params.username)
                    change_token(data.access_token)
                    navigate("/home");
                }
            }

        } catch (error) {
            console.log(error);
        } finally {
            setLoading(false)
        }
    }

    // ticket 获取usernama
    const getTicket = async () => {
        let paramsTicket = location.search.split("=")[1] || ''
        if (!paramsTicket) return
        try {

            let res = await checkTicket({ ticket: paramsTicket })
            let resJson = JSON.parse(res.data.data.replaceAll("'", '"'))
            if (!resJson.gid) return
            FormRef.current.setFieldsValue({
                username: resJson.gid,
                password: '123456'
            })
            getInfoSIte(resJson.gid)
            handleLogin()
        }
        catch (error) {
            console.log(error);
        }
    }

    // 获取site
    const getInfoSIte = async (name) => {
        try {
            let res2 = await getSiteInfo(name)
            var site = res2.data.data.site;
            if (site == '0') {
                let res3 = await listWorkshop()
                if (res3.data.code == 0) {
                    let siteList = res3.data.data;
                    change_site(siteList[0].no || '')
                }
            } else {
                let res3 = await listWorkshop()
                if (res3.data.code == 0) {
                    res3.data.data.forEach(item => {
                        if (item.no === site) {
                            change_site(item.no)
                            change_site_name(item.name)
                        }
                    });
                }
            }
        } catch (error) {
            console.log(error);
        }
    }

    return (
        <div className='login-page'>
            <Form layout='horizontal' ref={FormRef}>
                <Form.Item label='' name='username'>
                    <Input placeholder='请输入用户名' clearable />
                </Form.Item>
                <Form.Item
                    label=''
                    name='password'
                    extra={
                        <div className="eye">
                            {!visible ? (
                                <EyeInvisibleOutline fontSize={22} onClick={() => setVisible(true)} />
                            ) : (
                                <EyeOutline fontSize={22} onClick={() => setVisible(false)} />
                            )}
                        </div>
                    }
                >
                    <Input
                        placeholder='请输入密码'
                        clearable
                        type={visible ? 'text' : 'password'}
                    />
                </Form.Item>
            </Form>

            <Button loading={loading} type='primary' className="submitBtn" onClick={() => handleLogin()}>登 录</Button>
        </div>
    );
}

const mapStateToProps = (state) => {
    return {
        username: state.username,
    };
};

const mapDispatchToProps = {
    change_username,
    change_site,
    change_token,
    change_site_name
};


export default connect(mapStateToProps, mapDispatchToProps)(Index);

